package cn.itcast.bos.service.take_delivery.Impl;

import cn.itcast.bos.Dao.base.AreaDao;
import cn.itcast.bos.Dao.base.FixedAreaDao;
import cn.itcast.bos.Dao.take_delicery.OrderDao;
import cn.itcast.bos.Dao.take_delicery.WorkBillDao;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.constants.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private FixedAreaDao fixedAreaDao;
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private WorkBillDao workBillDao;
    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate jmsTemplate;
    @Override
    public void saveOrder(Order order) {
        //寄件人的省市区
        Area sendarea = order.getSendArea();
        Area persistArea = areaDao.findByProvinceAndCityAndDistrict(sendarea.getProvince(),sendarea.getCity(),sendarea.getDistrict());
        //将带有ID的area存入order中
        order.setSendArea(persistArea);
        //收件人的省市区
        Area recarea = order.getRecArea();
        Area recPersistArea = areaDao.findByProvinceAndCityAndDistrict(recarea.getProvince(),recarea.getCity(),recarea.getDistrict());
        order.setRecArea(recPersistArea);
        //生成订单编号
        String orderNum = UUID.randomUUID().toString();
        order.setOrderNum(orderNum);
        //生成订单时间
        order.setOrderTime(new Date());
        //生成订单状态
        order.setStatus("1");//待取件
        //根据order中的地址到crm_manange中查询是否与客户绑定的地址相同
        String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/crm_management/service/customerService/findFixedAreaIdByAddress?address="+order.getSendAddress()).
                accept(MediaType.APPLICATION_JSON).get(String.class);

        // 如果地址相同,自动分配快递员
        if(fixedAreaId !=null){
            FixedArea fixedArea = fixedAreaDao.findOne(fixedAreaId);
            Courier courier = fixedArea.getCouriers().iterator().next();
            if(courier !=null){
                System.out.println("自动分单完成");
                //将快递员关联到订单上
               saveOrder(order,courier);
               sendMsM(order);
               //发送短信
                return;
            }
        }
       /* 如果下单地址没有与 CRM 客户地址完全一致，从下单信息中 省、市、区 匹配区
        域信息，分区属于区域 ，获取区域中所有分区信息 ，获取分区关键字、辅助关键
        字，下单地址匹配分区关键字/辅助关键字，找到分区，通过分区找到定区，找到
        匹配快递员， 自动分单成功*/
       if(fixedAreaId ==null){
          for(SubArea subArea:persistArea.getSubareas()){
              //判断是否有对应的关键字
              if(order.getSendAddress().contains(subArea.getKeyWords()) ||order.getSendAddress().contains(subArea.getAssistKeyWords())){
                  //找到分区,找到定区,找到快递员
                  Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                  if(iterator.hasNext()){
                     Courier courier = iterator.next();
                     if(courier !=null){
                         System.out.println("自动分单成功..........");
                         //保存订单,发送短信
                         sendMsM(order);
                         saveOrder(order,courier);
                     }
                  }
              }
          }

       }
       //以上两种都不符合,进行人工分单
        order.setOrderType("2");
       orderDao.save(order);
    }

    @Override
    public Order findbyNum(String orderNum) {
        return orderDao.findByOrderNum(orderNum);
    }

    //自动保存订单的方法
    public void saveOrder(Order order,Courier courier){
        //将快递员关联到订单
        order.setCourier(courier);
        //设置订单状态为自动生成
        order.setOrderType("1");
        //保存订单
        orderDao.save(order);
    }
    //生成工单,调用MQ发送短信的方法
    public void sendMsM(final Order order){
        //设置新的工单
        WorkBill workBill = new WorkBill();
        workBill.setType("新");
        workBill.setPickstate("新单");
        workBill.setBuildtime(new Date());
        workBill.setRemark(order.getRemark());
        workBill.setOrder(order);
        workBill.setCourier(order.getCourier());
        final String smsNumber = RandomStringUtils.randomNumeric(6);
        workBill.setSmsNumber(smsNumber);
        //保存工单
        workBillDao.save(workBill);
        //调用mq发短信
        jmsTemplate.send("bos_sendMessage",     new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage =session.createMapMessage();
                mapMessage.setString("telephone", order.getCourier()
                        .getTelephone());
                mapMessage.setString(
                        "msg",
                        "短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress()
                                + ",联系人:" + order.getSendName() + ",手机:"
                                + order.getSendMobile() + "，快递员捎话："
                                + order.getSendMobileMsg());
                return mapMessage;
            }
        });
        //修改工单状态
        workBill.setPickstate("已通知");
    }

}
